import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:jtsell_app/entity/goods_detail_entity.dart';
import 'package:jtsell_app/network/http_dispense.dart';
import 'package:jtsell_app/provider/cart_list_model.dart';
import 'package:jtsell_app/provider/index_page_model.dart';
import 'package:jtsell_app/provider/main_category_model.dart';
import 'package:jtsell_app/r.dart';
import 'package:jtsell_app/widget/loading_widget.dart';
import 'package:provider/provider.dart';

import 'goods_cart.dart';
import 'goods_detail_comment.dart';
import 'goods_detail_html.dart';

class GoodsDetailPage extends StatefulWidget {
  final String goodsID;

  GoodsDetailPage({this.goodsID});

  @override
  _GoodsDetailPageState createState() => _GoodsDetailPageState(goodsID);
}

class _GoodsDetailPageState extends State<GoodsDetailPage> with SingleTickerProviderStateMixin {
  final String goodsID;

  _GoodsDetailPageState(this.goodsID);

  List<Tab> listTab;

  TabController _tabController;

  Color primaryColor;

  final TextStyle menuItemStyle =
      const PestoStyle(fontSize: 15.0, color: Colors.black54, height: 24.0 / 15.0);

  ///
  /// 生成菜单栏选项
  ///
  PopupMenuItem<String> _buildMenuItem(IconData icon, String label) {
    return PopupMenuItem<String>(
      child: Row(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(),
            child: Icon(icon, color: Colors.black54),
          ),
          Text(label, style: menuItemStyle),
        ],
      ),
    );
  }

  ///
  /// 备注栏
  ///
  Widget _getExplainWidget() {
    return Container(
      color: Color.fromRGBO(242, 240, 241, 100),
      height: ScreenUtil().setHeight(150),
      padding: EdgeInsets.only(top: ScreenUtil().setHeight(20), bottom: ScreenUtil().setHeight(20)),
      child: Container(
          width: ScreenUtil().setWidth(1080),
          color: Colors.white,
          child: Align(
            alignment: Alignment(-1, 0),
            child: Text(
              '说明：> 急速送达 > 正品保证',
              style: TextStyle(color: Colors.red, fontSize: ScreenUtil().setSp(40)),
            ),
          )),
    );
  }

  ///
  /// 获取完整的商品展示信息
  ///
  Widget _getGoodsDetailWidget(GoodsDetailEntity goodsDetailEntity) {
    return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [
          SliverAppBar(
            primary: true,
            floating: true,
            centerTitle: true,
            backgroundColor: Colors.white,
            expandedHeight: ScreenUtil().setHeight(1100),

            ///固定导航
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              collapseMode: CollapseMode.pin,
              background: Container(
                child: Column(
                  children: <Widget>[
                    FadeInImage.assetNetwork(
                        placeholder: R.IMG_600,
                        image: goodsDetailEntity.goodInfo.comPic,
                        fit: BoxFit.fitWidth,
                        height: ScreenUtil().setHeight(600)),
                    GoodsInfoWidget(goodsDetailEntity.goodInfo),
                    _getExplainWidget(),
                  ],
                ),
              ),
            ),
            bottom: TabBar(
              tabs: listTab,
              controller: _tabController,
              indicatorColor: primaryColor,
              labelColor: primaryColor,
              unselectedLabelColor: Colors.black54,
              indicatorSize: TabBarIndicatorSize.tab,
            ),

            leading: IconButton(
                icon: Icon(
                  Icons.arrow_back,
                  color: primaryColor,
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                }),
            actions: <Widget>[
              PopupMenuButton<String>(
                icon: Icon(
                  Icons.more_vert,
                  color: primaryColor,
                ),
                onSelected: (String item) {},
                itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                      _buildMenuItem(Icons.share, '分享'),
                      _buildMenuItem(Icons.email, '邮件'),
                    ],
              ),
            ],
          )
        ];
      },
      body: TabBarView(controller: _tabController, children: <Widget>[
        GoodsDetailHtml(goodsDetailEntity.goodInfo.goodsDetail),
        GoodsDetailComment(goodsDetailEntity.advertesPicture.pictureAddress),
      ]),
    );
  }

  @override
  void initState() {
    super.initState();

    ///
    /// 初始化时在第一帧获取context对象
    ///
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      primaryColor = Theme.of(context).primaryColor;
      listTab = <Tab>[Tab(child: Text("详情")), Tab(child: Text("评论"))];
    });

    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<GoodsDetailEntity>(
      future: HttpDispense.getGoodDetailById(goodsID),
      builder: (BuildContext context, AsyncSnapshot<GoodsDetailEntity> snapshot) {
        ///
        /// 加载未完成显示加载动画
        ///
        if (snapshot.connectionState != ConnectionState.done) {
          return LoadingWidget();
        }

        ///
        /// 加载错误页
        ///
        if (snapshot.hasError || !snapshot.hasData) {
          print(snapshot.error);
          return Scaffold(
            appBar: AppBar(
              title: Text(
                "商品详情",
              ),
            ),
            body: Center(
              child: Text("暂无数据"),
            ),
          );
        }

        GoodsDetailEntity goodsDetailEntity = snapshot.data;
        return SafeArea(
            child: Scaffold(
          body: Stack(
            children: <Widget>[
              _getGoodsDetailWidget(goodsDetailEntity),
              MultiProvider(
                providers: [
                  ChangeNotifierProvider<IndexPageModel>.value(value: indexPageModel),
                  ChangeNotifierProvider<CartListModel>.value(value: cartListModel),
                ],
                child: Positioned(left: 0, bottom: 0, child: GoodsCart(goodsDetailEntity)),
              ),
            ],
          ),
        ));
      },
    );
  }
}

///
/// 商品信息展示
///
class GoodsInfoWidget extends StatelessWidget {
  final GoodsDetailGoodinfo goodsInfo;

  GoodsInfoWidget(this.goodsInfo);

  ///
  /// 商品名称
  ///
  Widget _getGoodsName() {
    return Container(
      height: ScreenUtil().setHeight(60),
      width: ScreenUtil().setWidth(1000),
      child: Text(
        goodsInfo.goodsName,
        maxLines: 1,
        textAlign: TextAlign.left,
        style: TextStyle(fontSize: ScreenUtil().setSp(55)),
      ),
    );
  }

  ///
  ///  商品编号
  ///
  Widget _getGoodsNum() {
    return Container(
      height: ScreenUtil().setHeight(50),
      width: ScreenUtil().setWidth(1000),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
      child: Text(
        '编号: ${goodsInfo.goodsSerialNumber}',
        style: TextStyle(color: Colors.black26),
      ),
    );
  }

  ///
  /// 商品价格
  ///

  Widget _getGoodsPrice() {
    return Container(
      height: ScreenUtil().setHeight(65),
      width: ScreenUtil().setWidth(1000),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
      child: Row(
        children: <Widget>[
          Text(
            '￥${goodsInfo.presentPrice}',
            style: TextStyle(
              color: Colors.red,
              fontSize: ScreenUtil().setSp(60),
            ),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(15),
          ),
          Text(
            '市场价: ￥${goodsInfo.oriPrice}',
            style: TextStyle(color: Colors.black26, decoration: TextDecoration.lineThrough),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(1080),
      padding: EdgeInsets.all(ScreenUtil().setWidth(15)),
      child: Column(
        children: <Widget>[
          _getGoodsName(),
          _getGoodsNum(),
          _getGoodsPrice(),
        ],
      ),
    );
  }
}

class PestoStyle extends TextStyle {
  const PestoStyle({
    double fontSize = 12.0,
    FontWeight fontWeight,
    Color color = Colors.black87,
    double letterSpacing,
    double height,
  }) : super(
          inherit: false,
          color: color,
          fontFamily: 'Raleway',
          fontSize: fontSize,
          fontWeight: fontWeight,
          textBaseline: TextBaseline.alphabetic,
          letterSpacing: letterSpacing,
          height: height,
        );
}
